package com.ikingtech.framework.sdk.limit.mvc.configuration;

import com.ikingtech.framework.sdk.limit.config.properties.RateLimitProperties;
import com.ikingtech.framework.sdk.limit.embedded.RateLimiterService;
import com.ikingtech.framework.sdk.limit.mvc.MvcRateLimiterFactory;
import com.ikingtech.framework.sdk.limit.mvc.filter.MvcRateLimiterFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * @author zhangqiang
 */
public class MvcRateLimitConfiguration {

    @Bean
    @ConditionalOnBean(RequestMappingHandlerMapping.class)
    public MvcRateLimiterFactory rateLimiterFactory(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        return new MvcRateLimiterFactory(requestMappingHandlerMapping);
    }

    @Bean
    public FilterRegistrationBean<MvcRateLimiterFilter> rateLimiterFilterRegistration(MvcRateLimiterFilter mvcRateLimiterFilter) {
        FilterRegistrationBean<MvcRateLimiterFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(mvcRateLimiterFilter);
        registration.addUrlPatterns("/*");
        return registration;
    }

    @Bean
    public MvcRateLimiterFilter mvcRateLimiterFilter(RateLimitProperties rateLimitProperties,
                                                     RateLimiterService rateLimiterService) {
        return new MvcRateLimiterFilter(rateLimitProperties, rateLimiterService);
    }




}
